package com.googlecode.openrtp.grizzly.rtp.filter;

import com.googlecode.openrtp.grizzly.FilterAttributes;
import com.googlecode.openrtp.spi.PayloadType;
import com.googlecode.openrtp.spi.RtpPacket;
import com.googlecode.openrtp.spi.RtpSession;
import com.googlecode.openrtp.spi.SessionKeys;
import com.googlecode.openrtp.spi.annotation.Priority;
import java.io.IOException;
import java.util.logging.Logger;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.NextAction;

/**
 *
 * @author jocke
 */
@Priority(intValue = 200)
public class RtpPacketGenerateFilter extends BaseFilter {

    private static final Logger LOG = Logger.getLogger(RtpPacketGenerateFilter.class.getName());

    @Override
    public NextAction handleWrite(FilterChainContext ctx) throws IOException {
        
        final byte[] data = ctx.getMessage();
        
        RtpSession session = (RtpSession) ctx.getAttributes().getAttribute(FilterAttributes.SESSION);

        int v = 2;

        int p = 0;

        int x = 0;

        int cc = 0;

        int m = 0;

        int pt = session.lookup(SessionKeys.PAYLOAD_TYPE).getIntValue();

        int sn = (int) session.lookup(SessionKeys.SEQUNCE_NUMBER).incrementAndGet(); //TODO wrap around 65535

        long ts = System.currentTimeMillis();

        long ssrc = session.lookup(SessionKeys.SSRC);

        ctx.setMessage(RtpPacket.create(v, p, x, cc, m, pt, sn, ts, ssrc, data));

        return super.handleWrite(ctx);
    }
   

    @Override
    public NextAction handleRead(FilterChainContext ctx) throws IOException {
        return super.handleRead(ctx);
    }

}
